import Vue from "vue";
import VueRouter from "vue-router";

import Login from "../views/Login";
import Layout from "../layout/index.vue";
import ErrPage404 from "../views/ErrorPage/404.vue";

// 二级路由统一管理
import Page from "./page";
// error 报错页面
import errPage from "./error";


// 解决导航栏或者底部导航tabBar中的vue-router在3.0版本以上频繁点击菜单报错的问题。
const originalPush = VueRouter.prototype.push
VueRouter.prototype.push = function push(location) {
    return originalPush.call(this, location).catch(err => err)
}

Vue.use(VueRouter);

const routes = [
    ...errPage,
    {
        path: "/login",
        name: "login",
        component: Login,
    },
    {
        path: "/",
        name: "layout",
        component: Layout,
        children: [...Page],
        redirect: "/main",
    },
    {
        path: "*",
        component: ErrPage404,
    },
];

const router = new VueRouter({
    mode: "history",
    base: process.env.BASE_URL,
    routes,
});

// 白名单
const whiteList = [
    "/404",
    "/500",
    "/login",
    "/",
    "/main"
]

router.beforeEach((to, from, next) => {
    const token = window.localStorage.getItem("newtoken");
    // 把utils 本地存储的权限数据拿到 
    const authList = localStorage.getItem("authList") ? localStorage.getItem("authList").split(",") : [];
    // 登录鉴权
    if (!token && to.path !== "/login") {
        next("/login");
    } else {
        // 角色鉴权
        // 判断权限数组里的权限信息和我要去的路由信息匹不匹配 例如： 101 而我去的二级路由的路由信息meta里并没有101 那就去404 如果有就跳转
        // 并且要判断我白名单内的二级路由路径 和我要去的二级路由路径相不相同 如果相同就跳转 不同就404
        if (authList.some(item => item === to.meta.auth) || whiteList.some(item => item === to.path)) {
            next()
        } else {
            next("/404")
        }
    }
});


export default router;